package com.gaolang.web.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gaolang.web.entities.LoginLog;
import com.gaolang.web.entities.User;
import com.gaolang.web.mapper.LoginLogMapper;
import com.gaolang.web.service.ILoginLogService;
import com.gaolang.web.service.IUserService;
import com.gaolang.web.utils.AddressUtil;
import com.gaolang.web.utils.IPUtil;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Date;

/**
 * <p>
 * 登录日志表 服务实现类
 * </p>
 *
 * @author gaolang
 * @since 2021-03-03
 */
@Service
public class LoginLogServiceImpl extends ServiceImpl<LoginLogMapper, LoginLog> implements ILoginLogService {

    @Autowired
    private IUserService userService;

    @Override
    public LoginLog createLoginLog(HttpServletRequest request, Principal principal) {
        String username = principal.getName();
        User user = userService.getUserByUsername(username);
        LoginLog loginLog = new LoginLog();
        loginLog.setUsername(user.getUsername());
        loginLog.setIp(IPUtil.getIpAddr(request));
        loginLog.setLocation(AddressUtil.getCityInfo(IPUtil.getIpAddr(request)));
        //获取客服端操作系统
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        Browser browser = userAgent.getBrowser();
        OperatingSystem os = userAgent.getOperatingSystem();
        loginLog.setUserSystem(os.getName());
        loginLog.setUserBrowser(browser.getName());
        loginLog.setLoginTime(new Date());
        return loginLog;
    }

}
